/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.bht.esa.weather.resourcemanager;

import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * Verwaltet die Persistierung der WeatherResourceEntities
 * 
 * @author Andreas Goese
 * @author Sven Höche
 */
@Stateless
@LocalBean
public class WeatherResourceEntityManager {

    private EntityManager em;

    @PostConstruct
    private void initEntityManager() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("weatherResourcePU");
        this.em = emf.createEntityManager();
    }

    /**
     * Gibt ein Entity mit einer bestimmten Resource-Id zurück
     * 
     * @param resourceId
     * @return 
     */
    public WeatherResourceEntity getWeatherResourceEntity(String resourceId) {
        
        final CriteriaBuilder cb = em.getCriteriaBuilder();
        final CriteriaQuery<WeatherResourceEntity> query = cb.createQuery(WeatherResourceEntity.class);
        final Root<WeatherResourceEntity> root = query.from(WeatherResourceEntity.class);

        if (resourceId != null && resourceId.length() > 0) {
            final Predicate condition = cb.like(root.<String>get("resourceID"), resourceId);
            query.where(condition);
        }
        
        List<WeatherResourceEntity> resultList = em.createQuery(query).getResultList();
        if(resultList.size() > 0){
            return em.createQuery(query).getResultList().get(0);
        }else{
            return null;
        }
    }

    /**
     * Speichert ein WeatherResourceEntity in die Datenbank
     * @param entity Zu speicherndes Entitiy
     */
    public void saveWeatherResourceEntity(WeatherResourceEntity entity) {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.merge(entity);
        tx.commit();
    }
}
